import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { SearchVideoType } from 'src/redux/types';

interface SearchType {
  searchKey: string;
  videos: Array<SearchVideoType>;
  searchAttr: {
    page: number;
    pagecount: number;
  };
}

const initialState: SearchType = {
  searchKey: '',
  videos: [],
  searchAttr: {
    page: 1,
    pagecount: 1,
  },
};

export const SearchSlice = createSlice({
  name: 'sarch',
  initialState,
  reducers: {
    setSearchKey(state, action: PayloadAction<string>) {
      return { ...state, searchKey: action.payload };
    },
    setSearch(state, action: PayloadAction<Array<SearchVideoType>>) {
      return { ...state, videos: action.payload };
    },
    addSearch(state, action: PayloadAction<SearchVideoType>) {
      const { page, pagecount } = action.payload.value.attr;

      return {
        ...state,
        videos: [...state.videos, action.payload],
        searchAttr: { page, pagecount: Math.max(state.searchAttr.pagecount, pagecount) },
      };
    },
    clearVideosAndAttr(state) {
      return { ...state, videos: [], searchAttr: { page: 1, pagecount: 1 } };
    },
  },
});

export const actions = SearchSlice.actions;
